<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="基础信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                  <a-input :disabled="formDisabled" v-model="model.name" placeholder="请输入姓名"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="gender">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.gender"
                    dictCode="gender"
                    placeholder="请选择性别"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="民族" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="national">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.national"
                    dictCode="national"
                    placeholder="请选择民族"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="籍贯" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="nativePlace">
                  <j-area-linkage :disabled="formDisabled" type="cascader" v-model="model.nativePlace" placeholder="请选择籍贯"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="身份证号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="idCardNo">
                  <a-input :disabled="formDisabled" v-model="model.idCardNo" placeholder="请输入身份证号"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="身份证到期日" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="idCardNoDue">
                  <j-date :disabled="formDisabled" placeholder="请选择身份证到期日" v-model="model.idCardNoDue" style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="出生日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="birthDate">
                  <j-date placeholder="请选择出生日期" v-model="model.birthDate" style="width: 100%" disabled/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="2" header="资历状况">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="资格证书" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qualification">
                  <a-input :disabled="formDisabled" v-model="model.qualification" placeholder="请输入资格证书"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="职称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="professionalTitle">
                  <a-input :disabled="formDisabled" v-model="model.professionalTitle" placeholder="请输入职称"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="所学专业" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="major">
                  <a-input :disabled="formDisabled" v-model="model.major" placeholder="请输入专业"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="毕业时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="graduationDate">
                  <j-date
                    :disabled="formDisabled"
                    placeholder="请选择毕业时间"
                    v-model="model.graduationDate"
                    style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="最高学历/学位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="highestDegree">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.highestDegree"
                    dictCode="highest_degree"
                    placeholder="请选择最高学历"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="教育方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="educationalMode">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.educationalMode"
                    dictCode="educational_mode"
                    placeholder="请选择教育方式"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="3" header="组织信息" >
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="人员类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeType">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.employeeType"
                    dictCode="employee_type"
                    placeholder="请选择人员类型"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="人员状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="employeeStatus">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.employeeStatus"
                    dictCode="employee_status"
                    placeholder="请选择人员状态"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="工作地" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workplace">
                  <a-input :disabled="formDisabled" v-model="model.workplace" placeholder="请输入工作地"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="是否外派"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="expatriate">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.expatriate"
                    dictCode="YES_OR_NO"
                    placeholder="请选择是否外派"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="公积金单位"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  prop="providentFundUnit"
                >
                  <select-Company-input :disabled="formDisabled" v-model="model.providentFundUnit" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="参保单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="insuredUnit">
                  <select-Company-input :disabled="formDisabled" v-model="model.insuredUnit" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="4" header="资质证书">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-table
                  ref="table"
                  bordered
                  size="small"
                  rowKey="id"
                  :columns="childColumns"
                  :dataSource="model.employeeCertificateList"
                  :loading="false"
                  :pagination="false"
                >
                  <template slot="fileSlot" slot-scope="text">
                    <a @click="handleNewPre(text)">{{ text }}</a>
                  </template>
                </a-table>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel key="5" header="附件信息">
            <div>
              <div style="color: #f5222d;margin-bottom: 10px;">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</div>
            </div>
            <a-row :gutter="48">
              <a-col :span="6">
                <a-form-model-item label="身份证复印件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment.idCard">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.attachment.idCard" :showToast="false"></j-upload>
                  <view-upload v-else disabled v-model="model.attachment.idCard"></view-upload>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="毕业证复印件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment.graduate">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.attachment.graduate" :showToast="false"></j-upload>
                  <view-upload v-else disabled v-model="model.attachment.graduate"></view-upload>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="学位证复印件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment.degree">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.attachment.degree" :showToast="false"></j-upload>
                  <view-upload v-else disabled v-model="model.attachment.degree"></view-upload>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="学信网学历验证报告" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment.xuexin">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.attachment.xuexin" :showToast="false"></j-upload>
                  <view-upload v-else disabled v-model="model.attachment.xuexin"></view-upload>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="证件数码底版" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment.certificateBottom">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.attachment.certificateBottom" :showToast="false"></j-upload>
                  <view-upload v-else disabled v-model="model.attachment.certificateBottom"></view-upload>
                </a-form-model-item>
              </a-col>

              <a-col :span="6">
                <a-form-model-item label="劳动合同复印件" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment.employmentContract">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.attachment.employmentContract" :showToast="false"></j-upload>
                  <view-upload v-else disabled v-model="model.attachment.employmentContract"></view-upload>
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item label="证书" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment.certificate">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.attachment.certificate" :showToast="false"></j-upload>
                  <view-upload v-else disabled v-model="model.attachment.certificate"></view-upload>
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="6">
                <a-form-model-item label="其它" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment.other">
                  <j-upload v-if="!formDisabled" :disabled="formDisabled" v-model="model.attachment.other" :showToast="false"></j-upload>
                  <view-upload v-else disabled v-model="model.attachment.other"></view-upload>
                </a-form-model-item>
              </a-col> -->
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <watermark ref="watermarks" />
      <a-modal
        title="请选择预览或下载"
        :visible="prebtnVisible"
        :footer="null"
        @cancel="handleNewPreCancel"
        :width="240"
      >
        <div style="text-align: center;">
          <a-button shape="circle" icon="search" @click="handlePreviews(prebtnFile)"/>
          <a-divider type="vertical"/>
          <a-button shape="circle" icon="download" @click="handleModals(prebtnFile)"/>
        </div>
      </a-modal>
    </j-form-container>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { validateBlankValue, validateDuplicateValue } from '@/utils/util'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput';
import SelectPersonInput from '@/views/scy/components/SelectPersonInput'
import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import SelectFinanceKingdeeBankInput from '@/views/scy/components/SelectFinanceKingdeeBankInput'
import ViewUpload from '@/views/components/ViewUpload.vue'
import watermark from '@/views/erp/hr/certificatefile/companyQualification/modules/watermark.vue'
import PreviewPdf from '@/utils/previewPdfPublic'
import { axios } from '@/utils/request'
import { mapGetters } from 'vuex'

export default {
  name: 'ErpEmployeeFileFormDetail',
  components: {
    SelectFinanceKingdeeBankInput,
    SelectUserByDep,
    SelectCompanyInput,
    SelectTeamInput,
    SelectPersonInput,
    ViewUpload,
    watermark
  },
  props: {
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      activeKey: ['1', '2', '3', '4', '5'],
      model: {
        accountStatus: 'enabled',
        maritalStatus: '2',
        hasFamilyGeneticHistory: '0',
        hasInfectiousHistory: '0',
        hasPastMedicalHistory: '0',
        hasCriminalRecord: '0',
        expatriate: '0',
        gender: 'male',
        contactInfo: {},
        educationList: [],
        familySocialInfoList: [],
        positionChangeRecordList: [],
        rewardPunishFileList: [],
        trainingList: [],
        workHistoryList: [],
        employeeCertificateList: [],
        postChangeRecordList: [],
        attachment: {
          employeeId: ''
        }
      },
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 }
      },
      confirmLoading: false,
      validatorRules: {
        name: [
          { required: true, message: '请输入姓名!' },
          { validator: (rule, value, callback) => validateBlankValue('erp_employee_file', 'name', value, this.model.id, callback) }
        ],
        politicalLandscape: [
          { required: true, message: '请选择政治面貌!' }
        ],
        national: [
          { required: true, message: '请选择名族!' }
        ],
        nativePlace: [
          { required: true, message: '请选择籍贯!' }
        ],
        idCardNo: [
          { required: true, message: '请输入身份证号!' },
          { validator: (rule, value, callback) => validateDuplicateValue('erp_employee_file', 'id_card_no', value, this.model.id, callback) },
          { pattern: '^\\d{6}(18|19|20)?\\d{2}(0[1-9]|1[012])(0[1-9]|[12]\\d|3[01])\\d{3}(\\d|[xX])$', message: '身份证号格式不正确' }
        ],
        payeeName: [
          { required: true, message: '请输入员工的收款户名!' },
        ],
        idCardNoDue: [
          { required: true, message: '请选择身份证到期日!' }
        ],
        cnapsCode: [
          { required: true, message: '请选择员工的银行开户行联行号!' },
        ],
        bankName: [
          { required: true, message: '请输入员工的银行开户行!' },
        ],
        bankCard: [ { required: true, message: '请输入银行卡号!' },{ pattern: /^[1-9]{1}\d{7,50}$/, message: '银行卡号格式不正确' } ],
        departmentId: [
          { required: true, message: '请选择所属部门!' }
        ],
        orgDepart: [
          { required: true, message: '请选择所属单位!' }
        ],
        positionLevelId: [
          { required: true, message: '请选择职务级别!' }
        ],
        joinDate: [
          { required: true, message: '请选择入职时间!' }
        ],
        probationEndDate: [
          { required: true, message: '请选择转正时间!' }
        ],
        mainPost: [
          { required: true, message: '请选择主岗!' }
        ],
        deputyPost: [
          { required: true, message: '请选择副岗!' }
        ],
        expatriate: [
          { required: true, message: '请选择是否外派!' }
        ],
        payGradeId: [
          { required: true, message: '请选择薪级!' }
        ],
        workplace: [
          { required: true, message: '请输入工作地!' }
        ],
        teamId: [
          { required: true, message: '请选择所属团队!' }
        ],
        employeeType: [
          { required: true, message: '请选择人员状态!' }
        ],
        resignTime: [
          { required: true, message: '请选择离职日期!' }
        ],
        carSubsidy: [
          { required: false, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额！' }
        ],
        employeeStatus: [
          { required: true, message: '请选择人员类型!' }
        ],
        // reportId: [
        //   { required: true, message: '请选择汇报人!' }
        // ],
        providentFundUnit: [
            { required: true, message: '请选择公积金单位!' }
        ],
        providentFundBase: [
            { required: true, message: '请选择公积金基数!' }
        ],
        insuredUnit: [
            { required: true, message: '请选择参保单位!' }
        ],
        insuredBase: [
            { required: true, message: '请选择参保基数!' }
        ],
        contactInfo: {
          mobile: [{ required: true, pattern: /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/, message: '请输入正确手机号', trigger: 'blur' }],
          linkPerson: [
            { required: true, message: '请输入紧急联系人姓名!' }
          ],
          linkTel: [{ required: true, pattern: /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/, message: '请输入正确手机号', trigger: 'blur' }],
          email: [{ required: true, pattern: /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/, message: '请输入正确邮件地址', trigger: 'blur' }],
          idCardAddress: [{ required: true, message: '请输入身份证地址', trigger: 'blur' }],
          currentAddress: [{ required: true, message: '请输入身份证地址', trigger: 'blur' }]
        }
        // collapsePanel: [
        //   { required: true, message: '组织信息!' }
        // ]
      },
      url: {
        add: '/api/erp/files/employee/erpEmployeeFile/add',
        edit: '/api/erp/files/employee/erpEmployeeFile/edit',
        queryById: '/api/erp/files/employee/erpEmployeeFile/queryById',
        getEmployeeNoUrl: '/api/erpmng/sys/common/getDataSequenceNoByLen'
      },
      childColumns: [
        {
          title: '序号',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'证书名称',
          align:"center",
          dataIndex: 'certificateName',
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['certificateName'], text + '')
            }
          },
        },
        {
          title:'注册类别',
          align:"center",
          dataIndex: 'categoryId',
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['categoryId'], text + '')
            }
          },
        },
        {
          title:'注册专业',
          align:"center",
          dataIndex: 'professionalId',
          customRender: (text, r) => {
            if (!text) {
              return ''
            } else {
              return filterMultiDictText(this.dictOptions['professionalId'], text + '')
            }
          },
        },
        {
          title:'颁布时间',
          align:"center",
          dataIndex: 'issueDate',
        },
        {
          title:'颁发机构',
          align:"center",
          dataIndex: 'issueBody',
        },
        {
          title:'到期时间',
          align:"center",
          dataIndex: 'endDate',
        },
        {
          title:'继续教育时间',
          align:"center",
          dataIndex: 'educationDate',
        },
        {
          title:'附件',
          align:"center",
          dataIndex: 'attachment',
          scopedSlots: {customRender: 'fileSlot'}
        }
      ],
      prebtnVisible: false,
      prebtnFile: '',
      dictOptions: {}
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  methods: {
    ...mapGetters(['userInfo']),
    handleNewPre(value){
      this.prebtnVisible = true
      this.prebtnFile = value
    },
    handleNewPreCancel(){
      this.prebtnVisible = false
      this.prebtnFile = ''
    },
    handleModals(value){
      this.$refs.watermarks.visible = true
      this.$refs.watermarks.wValue = value
    },
    handlePreviews(value){
      let fileType = value.substr(-3)
      let text = `${this.userInfo().orgCodeTxt}-${this.userInfo().realname}-${this.userInfo().workNo}`
      let url = window.sessionStorage.getItem('baseUrl') + '/api/erpmng/sys/common/static/' + value
      axios({
        url: url,
        params: {},
        method:'get' ,
        responseType: 'blob',
      }).then(res=>{
        if(fileType==='pdf'){
          new PreviewPdf({
            blob: res,
            docTitle: fileType,
            isAddWatermark: true, // 是否需要添加水印
            watermark: { // watermark必填 里面可以不填
              type: 'canvas',
              text: text,
            }
          })
        }else{
          // location.href = url
          this.$message.error('非pdf文件不可查看')
        }
        
      })
    },
    async initDictConfig() {
      initDictOptions('erp_certificate_name_management,certificate_name,id').then(async(res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'certificateName', res.result)
        }
      })
    },
    async newInitDictConfig(){
      let res = await getAction('/api/erp/files/professional/erpProfessionalCategory/list', { pageNo: 1,pageSize: -1 })
      if (res.success) {
        let data = res.result.records || res.result
        if(data.length>0){
          this.$set(this.dictOptions, 'categoryId', data.map(v => {
            return {
              text: v.registrationCategory,
              title: v.registrationCategory,
              value: v.id
            }
          }))
          let newObj = []
          data.forEach(val => {
            if(val.children&&val.children.length>0){
              newObj.push(...val.children.map(c => {
                return {
                  text: c.registeredProfessional,
                  title: c.registeredProfessional,
                  value: c.id
                }
              }))
            }
          })
          this.$set(this.dictOptions, 'professionalId', newObj)
        }
      }
    },
    edit(record) {
      this.initDictConfig();
      this.newInitDictConfig()
      this.$refs.form.clearValidate()
      this.model.attachment.employeeId = record.id
      getAction(this.url.queryById, { id: record.id }).then(res => {
        if (res.success) {
          this.model = Object.assign({}, res.result)
        }
      })
      this.visible = true;
    },
  }
}
</script>
